package com.yc.jdbc;

import com.yc.spring.bank.bean.Account;
import com.yc.spring.bank.biz.AccountBiz;
import com.yc.spring.bank.biz.BizException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

// 该注解加在类上表示: 该类所有方法都支持事务
@Transactional
@Service
public class AccountBizImpl implements AccountBiz {
    @Resource
    JdbcTemplate jdbcTemplate;
    @Override
    public void register(Account account) {
        // 模板类 ==> 工具类
        jdbcTemplate.update("insert into bank_account values (?,'123',?)",
                account.getId(), account.getMoney());
    }

    @Override
    public void diposit(Integer id, double money)  throws BizException {
        jdbcTemplate.update(
                "update bank_account set balance = balance + ? where id= ?",
                money, id);
        if(money == 0){
            int i = 1/0;
        }
        jdbcTemplate.update("insert into bank_oprecord values " +
                "(null, ?, ? , null, now(), null)", id, money);
    }

    @Transactional(rollbackFor = BizException.class)
    // 转账
    public void transfer(int id1, int id2, double money) throws BizException{
        diposit(id1, - money);  // 取钱
        if(money == -1){
           throw new BizException("金额不能为 -1");
        }
        diposit(id2, + money);  // 存钱
    }

    public List<Account> selectAll(){
        String sql = "select * from bank_account";
        // queryForObject ==> 查询一行记录, 封装返回一个对象
        // query          ==> 查询多行数据, 返回 List 集合
        return jdbcTemplate.query(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getInt("id"));
                account.setMoney(rs.getDouble("balance"));
                return account;
            }
        });
    }
}
